import conf.settings as settings
from metric_reader import MetricReader
from lib.metric_type.capacity import CapacityMetric, Level
from lib.metric_exception import MetricSettingsException,\
    MetricCollectException, MetricProcessException

NODE_LABEL = settings.NODE_LABEL


# for node cpu util, need to use（1 - sysom_proc_cpu_total{mode="idle"}) to cal
class NodeCpuUtil(CapacityMetric):
    def __init__(self, metric_reader: MetricReader, metric_settings,
                 level: Level):
        super().__init__(metric_reader, metric_settings, level)

    def _collect_process_metric(self):
        if self.level != Level.Node:
            raise MetricSettingsException(
                f'{self.settings.collect.metric_name} is a node level metric!'
            )

        value = self.settings.collect.related_value[0]
        query_args = {
            NODE_LABEL: self.name[Level.Node],
            self.settings.collect.node_tag_name: value
        }

        res = self._get_custom_metric(self.settings.collect.metric_name,
                                      **query_args)

        if len(res.data) <= 0:
            raise MetricCollectException(
                f"Collect {self.settings.collect.metric_name}, Level:"
                f" {self.level} from Prometheus failed!"
            )

        try:
            max_values = []
            for i in range(len(res.data)):
                values = res.data[i].to_dict()["values"]
                # 区间值运算
                max_value = max(
                    (100 - float(value[1])) for value in values
                )
                max_values.append(max_value)
            final_value = max(max_values)
        except Exception as exc:
            raise MetricProcessException from exc

        return final_value
